/*
 * Copyright 2010 www.LongNet.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using LongNet.Web.Context;
using LongNet.Web.Mvc.Utils;

namespace LongNet.Web.Mvc.Processors {

    internal class ActionProcessor : ProcessorBase {

        private MvcContext ctx;

        public override void Process( ProcessContext context ) {

            MvcEventPublisher.Instance.BeginProcessAction( context.ctx );

            ControllerBase controller = context.getController();
            MethodInfo actionMethod = context.ctx.ActionMethodInfo; // context.getActionMethod();
            this.ctx = context.ctx;

            // 设值模板并载入全局变量
            setControllerView( controller, actionMethod );

            // 运行并处理post值
            ActionRunner.runAction( ctx, controller, actionMethod, controller.utils.runAction );
            String actionContent = controller.utils.getActionResult();
            actionContent = PostValueProcessor.ProcessPostValue( actionContent, ctx );

            if (ctx.utils.isAjax) {
                context.showEnd( actionContent );
            }
            else if (ctx.utils.isFrame()) {

                String content = MvcUtil.getFrameContent( actionContent );
                context.showEnd( content );
            }
            else if (ctx.utils.isEnd()) {
                context.showEnd( actionContent );
            }
            else {
                context.setContent( actionContent );
            }

        }


        private void setControllerView( ControllerBase controller, MethodInfo actionMethod ) {

            // 控制器继承
            if (actionMethod.DeclaringType != controller.GetType()) {
                String filePath = MvcUtil.getParentViewPath( actionMethod, controller.ctx.route.getRootNamespace() );
                controller.utils.setCurrentView( controller.utils.getTemplateByFileName( filePath ) );
            }
            else {
                controller.view( ctx.route.action );
            }
        }

    }

}
